/**
 * @file snakegamerenderer.cpp
 * @brief Snake游戏渲染引擎类实现文件
 *
 * 实现Snake游戏渲染引擎的所有功能，包括：
 * - 高性能游戏画面渲染
 * - 平滑动画和过渡效果
 * - 粒子系统和特效处理
 * - 主题管理和视觉效果
 * - 性能监控和优化
 */

#include "../include/snakegamerenderer.h"
#include <QDebug>               // 调试输出
#include <QPaintEvent>          // 绘制事件
#include <QResizeEvent>         // 调整大小事件
#include <QMouseEvent>          // 鼠标事件
#include <QWheelEvent>          // 滚轮事件
#include <QDateTime>            // 时间处理
#include <QJsonDocument>        // JSON文档处理
#include <QJsonObject>          // JSON对象处理
#include <QApplication>         // 应用程序
#include <QRandomGenerator>     // 随机数生成
#include <QtMath>               // 数学函数
#include <cmath>                // C数学函数

/**
 * @brief SnakeGameRenderer构造函数
 * @param parent 父窗口部件指针
 *
 * 初始化Snake游戏渲染引擎：
 * 1. 设置默认配置和状态
 * 2. 创建定时器和动画系统
 * 3. 加载主题和资源
 * 4. 初始化性能监控
 */
SnakeGameRenderer::SnakeGameRenderer(QWidget *parent)
    : QWidget(parent)
    , m_gameState(nullptr)
    , m_renderMode(Modern)
    , m_animationTimer(new QTimer(this))
    , m_fpsTimer(new QTimer(this))
    , m_animationProgress(0.0)
    , m_propertyAnimation(new QPropertyAnimation(this, "animationProgress", this))
    , m_particleTimer(new QTimer(this))
    , m_currentFPS(0.0)
    , m_lastFrameTime(0)
    , m_frameCount(0)
    , m_cacheValid(false)
    , m_backgroundColor(Qt::black)
    , m_gridColor(Qt::darkGray)
    , m_textColor(Qt::white)
{
    // === 初始化渲染器 ===
    initializeRenderer();
    
    qDebug() << "SnakeGameRenderer initialized";
}

/**
 * @brief SnakeGameRenderer析构函数
 */
SnakeGameRenderer::~SnakeGameRenderer()
{
    qDebug() << "SnakeGameRenderer destroyed";
}

/**
 * @brief 初始化渲染器
 */
void SnakeGameRenderer::initializeRenderer()
{
    // === 设置窗口属性 ===
    setMinimumSize(400, 300);
    setFocusPolicy(Qt::StrongFocus);
    setAttribute(Qt::WA_OpaquePaintEvent, true);
    setAttribute(Qt::WA_NoSystemBackground, true);
    
    // === 设置默认配置 ===
    m_config.cellSize = 20;
    m_config.gridLineWidth = 1;
    m_config.showGrid = true;
    m_config.enableAnimations = true;
    m_config.enableSmoothMovement = true;
    m_config.enableParticleEffects = true;
    m_config.targetFPS = 60;
    m_config.animationSpeed = 1.0;
    m_config.theme = "default";
    
    // === 设置动画定时器 ===
    m_animationTimer->setInterval(1000 / m_config.targetFPS); // 60 FPS
    m_animationTimer->setSingleShot(false);
    connect(m_animationTimer, &QTimer::timeout,
            this, &SnakeGameRenderer::onAnimationTimer);
    m_animationTimer->start();
    
    // === 设置FPS计算定时器 ===
    m_fpsTimer->setInterval(1000); // 每秒更新一次FPS
    m_fpsTimer->setSingleShot(false);
    connect(m_fpsTimer, &QTimer::timeout,
            this, &SnakeGameRenderer::onFPSTimer);
    m_fpsTimer->start();
    
    // === 设置粒子定时器 ===
    m_particleTimer->setInterval(16); // ~60 FPS
    m_particleTimer->setSingleShot(false);
    connect(m_particleTimer, &QTimer::timeout,
            this, &SnakeGameRenderer::updateParticles);
    m_particleTimer->start();
    
    // === 设置属性动画 ===
    m_propertyAnimation->setDuration(100);
    m_propertyAnimation->setEasingCurve(QEasingCurve::OutQuad);
    
    // === 加载主题 ===
    loadThemes();
    applyTheme(m_config.theme);
    
    // === 设置字体 ===
    m_gameFont = QFont("Arial", 12, QFont::Bold);
    
    // === 初始化性能监控 ===
    m_lastFrameTime = QDateTime::currentMSecsSinceEpoch();
}

/**
 * @brief 设置渲染配置
 * @param config 渲染配置
 */
void SnakeGameRenderer::setRenderConfig(const RenderConfig &config)
{
    m_config = config;
    
    // === 更新定时器间隔 ===
    if (m_config.targetFPS > 0) {
        m_animationTimer->setInterval(1000 / m_config.targetFPS);
    }
    
    // === 应用主题 ===
    if (!m_config.theme.isEmpty()) {
        applyTheme(m_config.theme);
    }
    
    // === 使缓存无效 ===
    invalidateCache();
    
    // === 触发重绘 ===
    update();
    
    qDebug() << "Render config updated - cellSize:" << m_config.cellSize 
             << "theme:" << m_config.theme << "FPS:" << m_config.targetFPS;
}

/**
 * @brief 设置游戏状态
 * @param gameState 游戏状态管理器
 */
void SnakeGameRenderer::setGameState(SnakeGameState *gameState)
{
    // === 断开旧连接 ===
    if (m_gameState) {
        disconnect(m_gameState, nullptr, this, nullptr);
    }
    
    m_gameState = gameState;
    
    // === 建立新连接 ===
    if (m_gameState) {
        connect(m_gameState, &SnakeGameState::stateUpdated,
                this, &SnakeGameRenderer::onGameStateUpdated);
        connect(m_gameState, &SnakeGameState::boardSizeChanged,
                this, [this](int width, int height) {
                    invalidateCache();
                    update();
                });
        connect(m_gameState, &SnakeGameState::foodConsumed,
                this, [this](const Position &position, const QString &playerId) {
                    playFoodConsumedEffect(position, "normal");
                });
        connect(m_gameState, &SnakeGameState::snakeDied,
                this, [this](const QString &playerId) {
                    const SnakeData* snake = m_gameState->getPlayerSnake(playerId);
                    if (snake) {
                        playSnakeDeathEffect(snake->body, snake->color);
                    }
                });
    }
    
    // === 使缓存无效并重绘 ===
    invalidateCache();
    update();
    
    qDebug() << "Game state set to renderer";
}

/**
 * @brief 设置渲染模式
 * @param mode 渲染模式
 */
void SnakeGameRenderer::setRenderMode(RenderMode mode)
{
    if (m_renderMode != mode) {
        m_renderMode = mode;
        
        // === 根据模式调整配置 ===
        switch (mode) {
        case Classic:
            m_config.enableAnimations = false;
            m_config.enableSmoothMovement = false;
            m_config.enableParticleEffects = false;
            m_config.showGrid = true;
            break;
        case Modern:
            m_config.enableAnimations = true;
            m_config.enableSmoothMovement = true;
            m_config.enableParticleEffects = true;
            m_config.showGrid = false;
            break;
        case Minimal:
            m_config.enableAnimations = false;
            m_config.enableSmoothMovement = false;
            m_config.enableParticleEffects = false;
            m_config.showGrid = false;
            break;
        case Retro:
            m_config.enableAnimations = false;
            m_config.enableSmoothMovement = false;
            m_config.enableParticleEffects = false;
            m_config.showGrid = true;
            break;
        }
        
        invalidateCache();
        update();
        
        qDebug() << "Render mode changed to:" << static_cast<int>(mode);
    }
}

/**
 * @brief 设置主题
 * @param themeName 主题名称
 */
void SnakeGameRenderer::setTheme(const QString &themeName)
{
    if (m_config.theme != themeName) {
        m_config.theme = themeName;
        applyTheme(themeName);
        invalidateCache();
        update();
        emit themeChanged(themeName);
        
        qDebug() << "Theme changed to:" << themeName;
    }
}

/**
 * @brief 获取可用主题列表
 * @return 主题名称列表
 */
QStringList SnakeGameRenderer::getAvailableThemes() const
{
    return m_themes.keys();
}

/**
 * @brief 启用/禁用动画
 * @param enabled 是否启用
 */
void SnakeGameRenderer::setAnimationsEnabled(bool enabled)
{
    m_config.enableAnimations = enabled;
    
    if (!enabled) {
        // === 停止所有动画 ===
        m_propertyAnimation->stop();
        m_snakeAnimations.clear();
        m_animationProgress = 0.0;
    }
    
    qDebug() << "Animations" << (enabled ? "enabled" : "disabled");
}

/**
 * @brief 设置动画速度
 * @param speed 速度倍数（1.0为正常速度）
 */
void SnakeGameRenderer::setAnimationSpeed(double speed)
{
    m_config.animationSpeed = qMax(0.1, qMin(5.0, speed)); // 限制在0.1-5.0之间
    
    // === 更新属性动画持续时间 ===
    int baseDuration = 100;
    int newDuration = static_cast<int>(baseDuration / m_config.animationSpeed);
    m_propertyAnimation->setDuration(newDuration);
    
    qDebug() << "Animation speed set to:" << m_config.animationSpeed;
}

/**
 * @brief 设置动画进度
 * @param progress 动画进度（0.0-1.0）
 */
void SnakeGameRenderer::setAnimationProgress(double progress)
{
    m_animationProgress = qMax(0.0, qMin(1.0, progress));
    
    if (m_config.enableAnimations) {
        update(); // 触发重绘以显示动画帧
    }
}

/**
 * @brief 添加粒子效果
 * @param position 位置
 * @param type 效果类型
 * @param color 颜色
 */
void SnakeGameRenderer::addParticleEffect(const Position &position, const QString &type, const QColor &color)
{
    if (!m_config.enableParticleEffects) {
        return;
    }
    
    // === 根据类型创建不同的粒子效果 ===
    int particleCount = 5;
    if (type == "food_consumed") {
        particleCount = 8;
    } else if (type == "snake_death") {
        particleCount = 15;
    }
    
    for (int i = 0; i < particleCount; ++i) {
        ParticleEffect particle;
        particle.position = position;
        particle.color = color;
        particle.size = 2.0 + QRandomGenerator::global()->generateDouble() * 3.0;
        particle.velocity = 1.0 + QRandomGenerator::global()->generateDouble() * 2.0;
        particle.angle = QRandomGenerator::global()->generateDouble() * 2 * M_PI;
        particle.life = 1.0;
        particle.decay = 0.01 + QRandomGenerator::global()->generateDouble() * 0.02;
        particle.type = type;
        particle.spawnTime = QDateTime::currentMSecsSinceEpoch();
        
        m_particles.append(particle);
    }
    
    qDebug() << "Added" << particleCount << "particles of type:" << type;
}

/**
 * @brief 清除所有粒子效果
 */
void SnakeGameRenderer::clearParticleEffects()
{
    m_particles.clear();
    qDebug() << "All particle effects cleared";
}

/**
 * @brief 播放食物消费效果
 * @param position 食物位置
 * @param foodType 食物类型
 */
void SnakeGameRenderer::playFoodConsumedEffect(const Position &position, const QString &foodType)
{
    QColor effectColor = getFoodColor(foodType);
    addParticleEffect(position, "food_consumed", effectColor);
}

/**
 * @brief 播放蛇死亡效果
 * @param snakeBody 蛇身体位置列表
 * @param color 蛇颜色
 */
void SnakeGameRenderer::playSnakeDeathEffect(const QVector<Position> &snakeBody, const QColor &color)
{
    // === 在蛇身体的每个位置添加粒子效果 ===
    for (const Position &pos : snakeBody) {
        addParticleEffect(pos, "snake_death", color);
    }
}

/**
 * @brief 获取当前FPS
 * @return 当前帧率
 */
double SnakeGameRenderer::getCurrentFPS() const
{
    return m_currentFPS;
}

/**
 * @brief 获取渲染统计信息
 * @return 统计信息JSON对象
 */
QJsonObject SnakeGameRenderer::getRenderStats() const
{
    QJsonObject stats;
    stats["current_fps"] = m_currentFPS;
    stats["target_fps"] = m_config.targetFPS;
    stats["frame_count"] = m_frameCount;
    stats["particle_count"] = m_particles.size();
    stats["animation_count"] = m_snakeAnimations.size();
    stats["cache_valid"] = m_cacheValid;
    stats["render_mode"] = static_cast<int>(m_renderMode);
    stats["theme"] = m_config.theme;
    stats["cell_size"] = m_config.cellSize;
    stats["animations_enabled"] = m_config.enableAnimations;
    stats["particles_enabled"] = m_config.enableParticleEffects;

    return stats;
}

/**
 * @brief 计算推荐窗口大小
 * @param boardWidth 游戏板宽度
 * @param boardHeight 游戏板高度
 * @return 推荐窗口大小
 */
QSize SnakeGameRenderer::calculateRecommendedSize(int boardWidth, int boardHeight) const
{
    int width = boardWidth * m_config.cellSize + 2 * m_config.gridLineWidth;
    int height = boardHeight * m_config.cellSize + 2 * m_config.gridLineWidth;

    // === 添加UI空间 ===
    height += 50; // 为状态栏等UI元素预留空间

    return QSize(width, height);
}

/**
 * @brief 像素坐标转换为游戏坐标
 * @param pixelPos 像素坐标
 * @return 游戏坐标
 */
Position SnakeGameRenderer::pixelToGamePosition(const QPoint &pixelPos) const
{
    int x = pixelPos.x() / m_config.cellSize;
    int y = pixelPos.y() / m_config.cellSize;
    return Position(x, y);
}

/**
 * @brief 游戏坐标转换为像素坐标
 * @param gamePos 游戏坐标
 * @return 像素坐标
 */
QPoint SnakeGameRenderer::gameToPixelPosition(const Position &gamePos) const
{
    int x = gamePos.x * m_config.cellSize;
    int y = gamePos.y * m_config.cellSize;
    return QPoint(x, y);
}

/**
 * @brief 绘制事件处理
 * @param event 绘制事件
 */
void SnakeGameRenderer::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event)

    qint64 frameStartTime = QDateTime::currentMSecsSinceEpoch();

    // === 创建绘图器 ===
    QPainter painter(this);
    setupPainter(painter);

    // === 绘制各个层次 ===
    drawBackground(painter);

    if (m_config.showGrid) {
        drawGrid(painter);
    }

    if (m_gameState) {
        drawFoods(painter);
        drawSnakes(painter);
    }

    if (m_config.enableParticleEffects) {
        drawParticles(painter);
    }

    drawUI(painter);

    // === 调试信息 ===
    if (m_config.showCoordinates) {
        drawDebugInfo(painter);
    }

    // === 更新性能统计 ===
    qint64 frameEndTime = QDateTime::currentMSecsSinceEpoch();
    double frameTime = frameEndTime - frameStartTime;
    m_frameTimes.enqueue(frameEndTime);
    m_frameCount++;

    emit frameRendered(frameTime);
}

/**
 * @brief 调整大小事件处理
 * @param event 调整大小事件
 */
void SnakeGameRenderer::resizeEvent(QResizeEvent *event)
{
    QWidget::resizeEvent(event);
    invalidateCache();
    qDebug() << "Renderer resized to:" << event->size();
}

/**
 * @brief 鼠标按下事件处理
 * @param event 鼠标事件
 */
void SnakeGameRenderer::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        Position gamePos = pixelToGamePosition(event->pos());
        qDebug() << "Mouse clicked at game position:" << gamePos.x << "," << gamePos.y;

        // === 可以在这里添加点击交互逻辑 ===
    }

    QWidget::mousePressEvent(event);
}

/**
 * @brief 鼠标移动事件处理
 * @param event 鼠标事件
 */
void SnakeGameRenderer::mouseMoveEvent(QMouseEvent *event)
{
    // === 可以在这里添加鼠标悬停效果 ===
    QWidget::mouseMoveEvent(event);
}

/**
 * @brief 滚轮事件处理
 * @param event 滚轮事件
 */
void SnakeGameRenderer::wheelEvent(QWheelEvent *event)
{
    // === 滚轮缩放功能 ===
    if (event->modifiers() & Qt::ControlModifier) {
        int delta = event->angleDelta().y();
        if (delta > 0) {
            // 放大
            m_config.cellSize = qMin(50, m_config.cellSize + 2);
        } else {
            // 缩小
            m_config.cellSize = qMax(10, m_config.cellSize - 2);
        }

        invalidateCache();
        update();

        qDebug() << "Cell size changed to:" << m_config.cellSize;
        event->accept();
    } else {
        QWidget::wheelEvent(event);
    }
}

/**
 * @brief 动画定时器处理
 */
void SnakeGameRenderer::onAnimationTimer()
{
    if (m_config.enableAnimations) {
        updateAnimations();
    }

    // === 触发重绘 ===
    update();
}

/**
 * @brief FPS计算定时器处理
 */
void SnakeGameRenderer::onFPSTimer()
{
    calculateFPS();
}

/**
 * @brief 游戏状态更新处理
 */
void SnakeGameRenderer::onGameStateUpdated()
{
    // === 启动动画（如果启用） ===
    if (m_config.enableAnimations && m_config.enableSmoothMovement) {
        m_propertyAnimation->stop();
        m_propertyAnimation->setStartValue(0.0);
        m_propertyAnimation->setEndValue(1.0);
        m_propertyAnimation->start();
    }

    // === 触发重绘 ===
    update();
}

/**
 * @brief 加载主题
 */
void SnakeGameRenderer::loadThemes()
{
    // === 默认主题 ===
    QJsonObject defaultTheme;
    defaultTheme["name"] = "Default";
    defaultTheme["background_color"] = "#000000";
    defaultTheme["grid_color"] = "#333333";
    defaultTheme["text_color"] = "#FFFFFF";

    QJsonArray defaultColors;
    defaultColors.append("#00FF00");
    defaultColors.append("#FF0000");
    defaultColors.append("#0000FF");
    defaultColors.append("#FFFF00");
    defaultTheme["snake_colors"] = defaultColors;

    defaultTheme["food_color"] = "#FF0000";
    defaultTheme["special_food_color"] = "#FFFF00";
    m_themes["default"] = defaultTheme;

    // === 深色主题 ===
    QJsonObject darkTheme;
    darkTheme["name"] = "Dark";
    darkTheme["background_color"] = "#1a1a1a";
    darkTheme["grid_color"] = "#404040";
    darkTheme["text_color"] = "#E0E0E0";

    QJsonArray darkColors;
    darkColors.append("#4CAF50");
    darkColors.append("#F44336");
    darkColors.append("#2196F3");
    darkColors.append("#FF9800");
    darkTheme["snake_colors"] = darkColors;

    darkTheme["food_color"] = "#E91E63";
    darkTheme["special_food_color"] = "#FFC107";
    m_themes["dark"] = darkTheme;

    // === 经典主题 ===
    QJsonObject classicTheme;
    classicTheme["name"] = "Classic";
    classicTheme["background_color"] = "#000000";
    classicTheme["grid_color"] = "#008000";
    classicTheme["text_color"] = "#00FF00";

    QJsonArray classicColors;
    classicColors.append("#00FF00");
    classicColors.append("#FFFF00");
    classicColors.append("#FF00FF");
    classicColors.append("#00FFFF");
    classicTheme["snake_colors"] = classicColors;

    classicTheme["food_color"] = "#FF0000";
    classicTheme["special_food_color"] = "#FFFFFF";
    m_themes["classic"] = classicTheme;

    // === 森林主题 ===
    QJsonObject forestTheme;
    forestTheme["name"] = "Forest";
    forestTheme["background_color"] = "#0d2818";
    forestTheme["grid_color"] = "#1a4d2e";
    forestTheme["text_color"] = "#90EE90";

    QJsonArray forestColors;
    forestColors.append("#228B22");
    forestColors.append("#32CD32");
    forestColors.append("#7CFC00");
    forestColors.append("#ADFF2F");
    forestTheme["snake_colors"] = forestColors;

    forestTheme["food_color"] = "#DC143C";
    forestTheme["special_food_color"] = "#FFD700";
    m_themes["forest"] = forestTheme;

    // === 海洋主题 ===
    QJsonObject oceanTheme;
    oceanTheme["name"] = "Ocean";
    oceanTheme["background_color"] = "#001f3f";
    oceanTheme["grid_color"] = "#004080";
    oceanTheme["text_color"] = "#87CEEB";

    QJsonArray oceanColors;
    oceanColors.append("#00CED1");
    oceanColors.append("#20B2AA");
    oceanColors.append("#48D1CC");
    oceanColors.append("#40E0D0");
    oceanTheme["snake_colors"] = oceanColors;

    oceanTheme["food_color"] = "#FF6347";
    oceanTheme["special_food_color"] = "#FFD700";
    m_themes["ocean"] = oceanTheme;

    // === 霓虹主题 ===
    QJsonObject neonTheme;
    neonTheme["name"] = "Neon";
    neonTheme["background_color"] = "#0a0a0a";
    neonTheme["grid_color"] = "#1a1a1a";
    neonTheme["text_color"] = "#00FFFF";

    QJsonArray neonColors;
    neonColors.append("#00FFFF");
    neonColors.append("#FF00FF");
    neonColors.append("#FFFF00");
    neonColors.append("#00FF00");
    neonTheme["snake_colors"] = neonColors;

    neonTheme["food_color"] = "#FF1493";
    neonTheme["special_food_color"] = "#00BFFF";
    m_themes["neon"] = neonTheme;

    // === 日落主题 ===
    QJsonObject sunsetTheme;
    sunsetTheme["name"] = "Sunset";
    sunsetTheme["background_color"] = "#2c1810";
    sunsetTheme["grid_color"] = "#4a2c1a";
    sunsetTheme["text_color"] = "#FFE4B5";

    QJsonArray sunsetColors;
    sunsetColors.append("#FF6347");
    sunsetColors.append("#FF7F50");
    sunsetColors.append("#FFA500");
    sunsetColors.append("#FFD700");
    sunsetTheme["snake_colors"] = sunsetColors;

    sunsetTheme["food_color"] = "#DC143C";
    sunsetTheme["special_food_color"] = "#FF69B4";
    m_themes["sunset"] = sunsetTheme;

    qDebug() << "Loaded" << m_themes.size() << "themes";
}

/**
 * @brief 应用主题
 * @param themeName 主题名称
 */
void SnakeGameRenderer::applyTheme(const QString &themeName)
{
    if (!m_themes.contains(themeName)) {
        qWarning() << "Theme not found:" << themeName;
        return;
    }

    QJsonObject theme = m_themes[themeName];

    // === 应用颜色 ===
    m_backgroundColor = QColor(theme["background_color"].toString());
    m_gridColor = QColor(theme["grid_color"].toString());
    m_textColor = QColor(theme["text_color"].toString());

    qDebug() << "Applied theme:" << themeName;
}

/**
 * @brief 更新动画
 */
void SnakeGameRenderer::updateAnimations()
{
    if (!m_gameState || !m_config.enableAnimations) {
        return;
    }

    qint64 currentTime = QDateTime::currentMSecsSinceEpoch();

    // === 更新蛇动画 ===
    for (auto it = m_snakeAnimations.begin(); it != m_snakeAnimations.end();) {
        AnimationState &anim = it.value();

        if (anim.active) {
            qint64 elapsed = currentTime - anim.startTime;
            anim.progress = qMin(1.0, static_cast<double>(elapsed) / anim.duration);

            if (anim.progress >= 1.0) {
                anim.active = false;
                it = m_snakeAnimations.erase(it);
            } else {
                ++it;
            }
        } else {
            ++it;
        }
    }
}

/**
 * @brief 更新粒子
 */
void SnakeGameRenderer::updateParticles()
{
    if (!m_config.enableParticleEffects) {
        return;
    }

    // === 更新粒子状态 ===
    for (auto it = m_particles.begin(); it != m_particles.end();) {
        ParticleEffect &particle = *it;

        // === 更新生命值 ===
        particle.life -= particle.decay;

        // === 更新位置 ===
        particle.position.x += particle.velocity * qCos(particle.angle) * 0.1;
        particle.position.y += particle.velocity * qSin(particle.angle) * 0.1;

        // === 更新大小 ===
        particle.size *= 0.98;

        // === 移除死亡的粒子 ===
        if (particle.life <= 0.0 || particle.size < 0.5) {
            it = m_particles.erase(it);
        } else {
            ++it;
        }
    }
}

/**
 * @brief 计算FPS
 */
void SnakeGameRenderer::calculateFPS()
{
    qint64 currentTime = QDateTime::currentMSecsSinceEpoch();

    // === 清理旧的帧时间 ===
    while (!m_frameTimes.isEmpty() && (currentTime - m_frameTimes.first()) > 1000) {
        m_frameTimes.dequeue();
    }

    // === 计算FPS ===
    if (!m_frameTimes.isEmpty()) {
        m_currentFPS = m_frameTimes.size();
        emit fpsUpdated(m_currentFPS);
    }
}

/**
 * @brief 使缓存无效
 */
void SnakeGameRenderer::invalidateCache()
{
    m_cacheValid = false;
    m_backgroundCache = QPixmap();
    m_gridCache = QPixmap();
}

/**
 * @brief 绘制背景
 * @param painter 绘图器
 */
void SnakeGameRenderer::drawBackground(QPainter &painter)
{
    QRect backgroundRect = rect();

    switch (m_renderMode) {
    case Classic:
    case Retro:
        // === 经典模式：纯色背景 ===
        painter.fillRect(backgroundRect, m_backgroundColor);
        break;

    case Modern:
        // === 现代模式：渐变背景 ===
        {
            QLinearGradient backgroundGradient(0, 0, backgroundRect.width(), backgroundRect.height());
            backgroundGradient.setColorAt(0.0, m_backgroundColor);
            backgroundGradient.setColorAt(0.5, m_backgroundColor.lighter(105));
            backgroundGradient.setColorAt(1.0, m_backgroundColor.darker(105));

            painter.fillRect(backgroundRect, QBrush(backgroundGradient));

            // === 添加微妙的纹理效果 ===
            if (m_gameState && m_gameState->getBoardWidth() > 0) {
                painter.setOpacity(0.03);
                painter.setPen(QPen(m_textColor, 1));

                int cellSize = m_config.cellSize;
                for (int x = 0; x < backgroundRect.width(); x += cellSize * 2) {
                    for (int y = 0; y < backgroundRect.height(); y += cellSize * 2) {
                        if ((x / cellSize + y / cellSize) % 2 == 0) {
                            painter.fillRect(x, y, cellSize, cellSize, m_textColor);
                        }
                    }
                }
                painter.setOpacity(1.0);
            }
        }
        break;

    case Minimal:
        // === 简约模式：纯白背景 ===
        painter.fillRect(backgroundRect, QColor(250, 250, 250));
        break;
    }
}

/**
 * @brief 绘制网格
 * @param painter 绘图器
 */
void SnakeGameRenderer::drawGrid(QPainter &painter)
{
    if (!m_gameState) {
        return;
    }

    int boardWidth = m_gameState->getBoardWidth();
    int boardHeight = m_gameState->getBoardHeight();

    switch (m_renderMode) {
    case Classic:
    case Retro:
        // === 经典模式：实线网格 ===
        painter.setPen(QPen(m_gridColor, m_config.gridLineWidth));

        for (int x = 0; x <= boardWidth; ++x) {
            int pixelX = x * m_config.cellSize;
            painter.drawLine(pixelX, 0, pixelX, boardHeight * m_config.cellSize);
        }

        for (int y = 0; y <= boardHeight; ++y) {
            int pixelY = y * m_config.cellSize;
            painter.drawLine(0, pixelY, boardWidth * m_config.cellSize, pixelY);
        }
        break;

    case Modern:
        // === 现代模式：虚线网格 + 点状装饰 ===
        {
            QColor lightGridColor = m_gridColor;
            lightGridColor.setAlpha(60);
            painter.setPen(QPen(lightGridColor, 1, Qt::DotLine));

            // 绘制主网格线
            for (int x = 0; x <= boardWidth; x += 5) {
                int pixelX = x * m_config.cellSize;
                painter.drawLine(pixelX, 0, pixelX, boardHeight * m_config.cellSize);
            }

            for (int y = 0; y <= boardHeight; y += 5) {
                int pixelY = y * m_config.cellSize;
                painter.drawLine(0, pixelY, boardWidth * m_config.cellSize, pixelY);
            }

            // 绘制细网格点
            lightGridColor.setAlpha(30);
            painter.setPen(QPen(lightGridColor, 1));
            painter.setBrush(lightGridColor);

            for (int x = 0; x < boardWidth; x += 2) {
                for (int y = 0; y < boardHeight; y += 2) {
                    QPoint center(x * m_config.cellSize + m_config.cellSize/2,
                                 y * m_config.cellSize + m_config.cellSize/2);
                    painter.drawEllipse(center, 1, 1);
                }
            }
        }
        break;

    case Minimal:
        // === 简约模式：无网格或极简网格 ===
        if (m_config.showGrid) {
            QColor veryLightGrid = m_gridColor;
            veryLightGrid.setAlpha(20);
            painter.setPen(QPen(veryLightGrid, 1));

            // 只绘制边界
            QRect boardRect(0, 0, boardWidth * m_config.cellSize, boardHeight * m_config.cellSize);
            painter.drawRect(boardRect);
        }
        break;
    }
}

/**
 * @brief 绘制所有蛇
 * @param painter 绘图器
 */
void SnakeGameRenderer::drawSnakes(QPainter &painter)
{
    if (!m_gameState) {
        return;
    }

    const QVector<SnakeData> &snakes = m_gameState->getSnakes();
    for (const SnakeData &snake : snakes) {
        if (snake.isAlive) {
            drawSnake(painter, snake);
        }
    }
}

/**
 * @brief 绘制单条蛇
 * @param painter 绘图器
 * @param snake 蛇数据
 */
void SnakeGameRenderer::drawSnake(QPainter &painter, const SnakeData &snake)
{
    if (snake.body.isEmpty()) {
        return;
    }

    // === 设置蛇的颜色 ===
    QColor bodyColor = getSnakeColor(snake.playerId, false);
    QColor headColor = getSnakeColor(snake.playerId, true);

    // === 绘制蛇身 ===
    for (int i = 1; i < snake.body.size(); ++i) {
        Position pos = snake.body[i];

        // === 应用动画插值 ===
        if (m_config.enableSmoothMovement && m_animationProgress < 1.0) {
            if (i == snake.body.size() - 1) { // 蛇尾
                // 蛇尾可能需要特殊的动画处理
            }
        }

        QRect cellRect = getCellRect(pos);

        // === 计算渐变颜色（从头到尾逐渐变暗） ===
        double fadeRatio = 1.0 - (double(i) / snake.body.size()) * 0.3; // 最多变暗30%
        QColor segmentColor = bodyColor;
        segmentColor = segmentColor.darker(100 + (1.0 - fadeRatio) * 50);

        // === 根据渲染模式绘制蛇身 ===
        switch (m_renderMode) {
        case Classic:
        case Retro:
            // === 经典模式：添加边框效果 ===
            painter.fillRect(cellRect, segmentColor);
            painter.setPen(QPen(segmentColor.darker(150), 1));
            painter.drawRect(cellRect);
            break;

        case Modern:
            {
                // === 现代模式：3D效果和渐变 ===
                painter.setRenderHint(QPainter::Antialiasing, true);

                // 创建径向渐变
                QRadialGradient gradient(cellRect.center(), m_config.cellSize * 0.6);
                gradient.setColorAt(0.0, segmentColor.lighter(130));
                gradient.setColorAt(0.7, segmentColor);
                gradient.setColorAt(1.0, segmentColor.darker(120));

                painter.setBrush(QBrush(gradient));
                painter.setPen(QPen(segmentColor.darker(150), 1));

                // 绘制圆角矩形
                int radius = m_config.cellSize / 6;
                painter.drawRoundedRect(cellRect.adjusted(1, 1, -1, -1), radius, radius);

                // 添加高光效果
                QRect highlightRect = cellRect.adjusted(2, 2, -cellRect.width()/2, -cellRect.height()/2);
                painter.setBrush(QColor(255, 255, 255, 40));
                painter.setPen(Qt::NoPen);
                painter.drawRoundedRect(highlightRect, radius/2, radius/2);
                break;
            }

        case Minimal:
            {
                // === 简约模式：干净的线条 ===
                QRect adjustedRect = cellRect.adjusted(2, 2, -2, -2);
                painter.fillRect(adjustedRect, segmentColor);
                break;
            }
        }
    }

    // === 绘制蛇头 ===
    if (!snake.body.isEmpty()) {
        Position headPos = snake.body.first();

        // === 应用动画插值 ===
        if (m_config.enableSmoothMovement && m_animationProgress < 1.0) {
            // 计算插值位置
            Position prevPos = headPos;
            if (snake.body.size() > 1) {
                prevPos = snake.body[1];
            }
            headPos = interpolatePosition(prevPos, headPos, m_animationProgress);
        }

        QRect headRect = getCellRect(headPos);

        // === 根据渲染模式绘制蛇头 ===
        switch (m_renderMode) {
        case Classic:
        case Retro:
            // === 经典模式：带边框的方形头 ===
            painter.fillRect(headRect, headColor);
            painter.setPen(QPen(headColor.darker(150), 2));
            painter.drawRect(headRect);
            break;

        case Modern:
            {
                // === 现代模式：3D椭圆头部 ===
                painter.setRenderHint(QPainter::Antialiasing, true);

                // 创建径向渐变
                QRadialGradient headGradient(headRect.center(), m_config.cellSize * 0.7);
                headGradient.setColorAt(0.0, headColor.lighter(140));
                headGradient.setColorAt(0.6, headColor);
                headGradient.setColorAt(1.0, headColor.darker(130));

                painter.setBrush(QBrush(headGradient));
                painter.setPen(QPen(headColor.darker(150), 2));
                painter.drawEllipse(headRect.adjusted(1, 1, -1, -1));

                // 添加高光
                QRect highlightRect = headRect.adjusted(3, 3, -headRect.width()/2, -headRect.height()/2);
                painter.setBrush(QColor(255, 255, 255, 60));
                painter.setPen(Qt::NoPen);
                painter.drawEllipse(highlightRect);
                break;
            }

        case Minimal:
            {
                // === 简约模式：小圆点 ===
                QRect adjustedRect = headRect.adjusted(3, 3, -3, -3);
                painter.setRenderHint(QPainter::Antialiasing, true);
                painter.setBrush(headColor);
                painter.setPen(Qt::NoPen);
                painter.drawEllipse(adjustedRect);
                break;
            }
        }

        // === 绘制眼睛和表情 ===
        if (m_renderMode == Modern) {
            drawSnakeEyes(painter, headRect, snake.direction, snake.isAlive);

            // 如果蛇死了，绘制X眼睛
            if (!snake.isAlive) {
                drawDeadSnakeEyes(painter, headRect);
            }
        }
    }
}

/**
 * @brief 绘制蛇的眼睛
 * @param painter 绘图器
 * @param headRect 蛇头矩形
 * @param direction 移动方向
 * @param isAlive 是否存活
 */
void SnakeGameRenderer::drawSnakeEyes(QPainter &painter, const QRect &headRect, Direction direction, bool isAlive)
{
    if (!isAlive) return;

    painter.setRenderHint(QPainter::Antialiasing, true);

    int eyeSize = qMax(3, m_config.cellSize / 8);
    int pupilSize = qMax(2, eyeSize / 2);
    int eyeOffset = m_config.cellSize / 5;

    // === 根据方向计算眼睛位置 ===
    QPoint eyePos1, eyePos2;
    switch (direction) {
    case Direction::Up:
        eyePos1 = headRect.center() + QPoint(-eyeOffset, -eyeOffset);
        eyePos2 = headRect.center() + QPoint(eyeOffset, -eyeOffset);
        break;
    case Direction::Down:
        eyePos1 = headRect.center() + QPoint(-eyeOffset, eyeOffset);
        eyePos2 = headRect.center() + QPoint(eyeOffset, eyeOffset);
        break;
    case Direction::Left:
        eyePos1 = headRect.center() + QPoint(-eyeOffset, -eyeOffset);
        eyePos2 = headRect.center() + QPoint(-eyeOffset, eyeOffset);
        break;
    case Direction::Right:
        eyePos1 = headRect.center() + QPoint(eyeOffset, -eyeOffset);
        eyePos2 = headRect.center() + QPoint(eyeOffset, eyeOffset);
        break;
    }

    // === 绘制眼白 ===
    painter.setBrush(Qt::white);
    painter.setPen(QPen(Qt::black, 1));
    painter.drawEllipse(eyePos1, eyeSize, eyeSize);
    painter.drawEllipse(eyePos2, eyeSize, eyeSize);

    // === 绘制瞳孔 ===
    painter.setBrush(Qt::black);
    painter.setPen(Qt::NoPen);

    // 瞳孔稍微偏向移动方向
    QPoint pupilOffset(0, 0);
    switch (direction) {
    case Direction::Up:    pupilOffset = QPoint(0, -1); break;
    case Direction::Down:  pupilOffset = QPoint(0, 1); break;
    case Direction::Left:  pupilOffset = QPoint(-1, 0); break;
    case Direction::Right: pupilOffset = QPoint(1, 0); break;
    }

    painter.drawEllipse(eyePos1 + pupilOffset, pupilSize, pupilSize);
    painter.drawEllipse(eyePos2 + pupilOffset, pupilSize, pupilSize);

    // === 添加眼睛高光 ===
    painter.setBrush(Qt::white);
    int highlightSize = qMax(1, pupilSize / 3);
    painter.drawEllipse(eyePos1 + pupilOffset + QPoint(-1, -1), highlightSize, highlightSize);
    painter.drawEllipse(eyePos2 + pupilOffset + QPoint(-1, -1), highlightSize, highlightSize);
}

/**
 * @brief 绘制死亡蛇的X眼睛
 * @param painter 绘图器
 * @param headRect 蛇头矩形
 */
void SnakeGameRenderer::drawDeadSnakeEyes(QPainter &painter, const QRect &headRect)
{
    painter.setRenderHint(QPainter::Antialiasing, true);
    painter.setPen(QPen(Qt::red, 2, Qt::SolidLine, Qt::RoundCap));

    int eyeSize = m_config.cellSize / 6;
    int eyeOffset = m_config.cellSize / 5;

    // === 左眼X ===
    QPoint leftEyeCenter = headRect.center() + QPoint(-eyeOffset, 0);
    painter.drawLine(leftEyeCenter + QPoint(-eyeSize/2, -eyeSize/2),
                     leftEyeCenter + QPoint(eyeSize/2, eyeSize/2));
    painter.drawLine(leftEyeCenter + QPoint(-eyeSize/2, eyeSize/2),
                     leftEyeCenter + QPoint(eyeSize/2, -eyeSize/2));

    // === 右眼X ===
    QPoint rightEyeCenter = headRect.center() + QPoint(eyeOffset, 0);
    painter.drawLine(rightEyeCenter + QPoint(-eyeSize/2, -eyeSize/2),
                     rightEyeCenter + QPoint(eyeSize/2, eyeSize/2));
    painter.drawLine(rightEyeCenter + QPoint(-eyeSize/2, eyeSize/2),
                     rightEyeCenter + QPoint(eyeSize/2, -eyeSize/2));
}

/**
 * @brief 绘制所有食物
 * @param painter 绘图器
 */
void SnakeGameRenderer::drawFoods(QPainter &painter)
{
    if (!m_gameState) {
        return;
    }

    const QVector<FoodData> &foods = m_gameState->getFoods();
    for (const FoodData &food : foods) {
        drawFood(painter, food);
    }
}

/**
 * @brief 绘制单个食物
 * @param painter 绘图器
 * @param food 食物数据
 */
void SnakeGameRenderer::drawFood(QPainter &painter, const FoodData &food)
{
    QRect cellRect = getCellRect(food.position);
    QColor foodColor = getFoodColor(food.type);

    // === 添加闪烁效果（特殊食物） ===
    if (food.isSpecial) {
        qint64 currentTime = QDateTime::currentMSecsSinceEpoch();
        double pulsePhase = (currentTime % 1000) / 1000.0 * 2 * M_PI;
        double pulseFactor = 0.8 + 0.2 * qSin(pulsePhase);
        foodColor = foodColor.lighter(100 + 30 * pulseFactor);
    }

    // === 根据渲染模式绘制食物 ===
    switch (m_renderMode) {
    case Classic:
    case Retro:
        // === 经典模式：像素风格 ===
        painter.fillRect(cellRect, foodColor);
        painter.setPen(QPen(foodColor.darker(150), 1));
        painter.drawRect(cellRect);
        break;

    case Modern:
        painter.setRenderHint(QPainter::Antialiasing, true);

        if (food.isSpecial) {
            // === 特殊食物：闪亮的星形 ===
            drawSpecialFood(painter, cellRect, foodColor);
        } else {
            // === 普通食物：3D苹果效果 ===
            drawNormalFood(painter, cellRect, foodColor);
        }
        break;

    case Minimal:
        {
            // === 简约模式：小圆点 ===
            QRect adjustedRect = cellRect.adjusted(4, 4, -4, -4);
            painter.setRenderHint(QPainter::Antialiasing, true);
            painter.setBrush(foodColor);
            painter.setPen(Qt::NoPen);
            painter.drawEllipse(adjustedRect);
            break;
        }
    }
}

/**
 * @brief 绘制普通食物（苹果样式）
 * @param painter 绘图器
 * @param cellRect 单元格矩形
 * @param baseColor 基础颜色
 */
void SnakeGameRenderer::drawNormalFood(QPainter &painter, const QRect &cellRect, const QColor &baseColor)
{
    painter.setRenderHint(QPainter::Antialiasing, true);

    // === 绘制苹果主体 ===
    QRect appleRect = cellRect.adjusted(2, 3, -2, -2);

    // 创建径向渐变
    QRadialGradient appleGradient(appleRect.center() + QPoint(-2, -2), appleRect.width() * 0.6);
    appleGradient.setColorAt(0.0, baseColor.lighter(140));
    appleGradient.setColorAt(0.7, baseColor);
    appleGradient.setColorAt(1.0, baseColor.darker(120));

    painter.setBrush(QBrush(appleGradient));
    painter.setPen(QPen(baseColor.darker(150), 1));
    painter.drawEllipse(appleRect);

    // === 绘制苹果叶子 ===
    QRect leafRect = QRect(cellRect.center().x() + 1, cellRect.top() + 1, 4, 6);
    painter.setBrush(QColor(34, 139, 34)); // 森林绿
    painter.setPen(Qt::NoPen);
    painter.drawEllipse(leafRect);

    // === 添加高光 ===
    QRect highlightRect = appleRect.adjusted(2, 2, -appleRect.width()/2, -appleRect.height()/2);
    painter.setBrush(QColor(255, 255, 255, 80));
    painter.setPen(Qt::NoPen);
    painter.drawEllipse(highlightRect);
}

/**
 * @brief 绘制特殊食物（钻石样式）
 * @param painter 绘图器
 * @param cellRect 单元格矩形
 * @param baseColor 基础颜色
 */
void SnakeGameRenderer::drawSpecialFood(QPainter &painter, const QRect &cellRect, const QColor &baseColor)
{
    painter.setRenderHint(QPainter::Antialiasing, true);

    QPoint center = cellRect.center();
    int size = m_config.cellSize / 3;

    // === 创建钻石形状 ===
    QPolygon diamond;
    diamond << QPoint(center.x(), center.y() - size)      // 顶部
            << QPoint(center.x() + size, center.y())      // 右侧
            << QPoint(center.x(), center.y() + size)      // 底部
            << QPoint(center.x() - size, center.y());     // 左侧

    // === 绘制钻石主体 ===
    QLinearGradient diamondGradient(center.x() - size, center.y() - size,
                                   center.x() + size, center.y() + size);
    diamondGradient.setColorAt(0.0, baseColor.lighter(160));
    diamondGradient.setColorAt(0.5, baseColor);
    diamondGradient.setColorAt(1.0, baseColor.darker(130));

    painter.setBrush(QBrush(diamondGradient));
    painter.setPen(QPen(baseColor.darker(150), 2));
    painter.drawPolygon(diamond);

    // === 添加内部闪光效果 ===
    QPolygon innerDiamond;
    int innerSize = size * 0.6;
    innerDiamond << QPoint(center.x(), center.y() - innerSize)
                 << QPoint(center.x() + innerSize, center.y())
                 << QPoint(center.x(), center.y() + innerSize)
                 << QPoint(center.x() - innerSize, center.y());

    painter.setBrush(QColor(255, 255, 255, 60));
    painter.setPen(Qt::NoPen);
    painter.drawPolygon(innerDiamond);

    // === 添加星光效果 ===
    painter.setPen(QPen(Qt::white, 1));
    painter.drawLine(center.x() - size - 2, center.y(), center.x() + size + 2, center.y());
    painter.drawLine(center.x(), center.y() - size - 2, center.x(), center.y() + size + 2);
}

/**
 * @brief 绘制粒子效果
 * @param painter 绘图器
 */
void SnakeGameRenderer::drawParticles(QPainter &painter)
{
    if (!m_config.enableParticleEffects || m_particles.isEmpty()) {
        return;
    }

    painter.setRenderHint(QPainter::Antialiasing, true);

    for (const ParticleEffect &particle : m_particles) {
        // === 计算粒子的实际位置和大小 ===
        QPointF pixelPos = QPointF(particle.position.x * m_config.cellSize + m_config.cellSize/2,
                                  particle.position.y * m_config.cellSize + m_config.cellSize/2);

        // === 根据生命值调整透明度和大小 ===
        QColor particleColor = particle.color;
        particleColor.setAlphaF(particle.life);

        double currentSize = particle.size * particle.life;

        // === 根据粒子类型绘制不同效果 ===
        if (particle.type == "food_consumed") {
            // === 食物消费粒子：闪亮的星星 ===
            drawStarParticle(painter, pixelPos, currentSize, particleColor);
        } else if (particle.type == "snake_death") {
            // === 蛇死亡粒子：爆炸碎片 ===
            drawExplosionParticle(painter, pixelPos, currentSize, particleColor);
        } else {
            // === 默认粒子：简单圆形 ===
            painter.setBrush(particleColor);
            painter.setPen(Qt::NoPen);
            painter.drawEllipse(pixelPos, currentSize, currentSize);
        }
    }
}

/**
 * @brief 绘制星星粒子
 * @param painter 绘图器
 * @param center 中心位置
 * @param size 大小
 * @param color 颜色
 */
void SnakeGameRenderer::drawStarParticle(QPainter &painter, const QPointF &center, double size, const QColor &color)
{
    // === 创建星形 ===
    QPolygonF star;
    int points = 5;
    double outerRadius = size;
    double innerRadius = size * 0.4;

    for (int i = 0; i < points * 2; ++i) {
        double angle = i * M_PI / points;
        double radius = (i % 2 == 0) ? outerRadius : innerRadius;
        double x = center.x() + radius * qCos(angle);
        double y = center.y() + radius * qSin(angle);
        star << QPointF(x, y);
    }

    // === 绘制星形主体 ===
    QRadialGradient starGradient(center, outerRadius);
    starGradient.setColorAt(0.0, color.lighter(150));
    starGradient.setColorAt(0.7, color);
    starGradient.setColorAt(1.0, color.darker(120));

    painter.setBrush(QBrush(starGradient));
    painter.setPen(QPen(color.lighter(180), 1));
    painter.drawPolygon(star);
}

/**
 * @brief 绘制爆炸粒子
 * @param painter 绘图器
 * @param center 中心位置
 * @param size 大小
 * @param color 颜色
 */
void SnakeGameRenderer::drawExplosionParticle(QPainter &painter, const QPointF &center, double size, const QColor &color)
{
    // === 创建不规则碎片形状 ===
    QPolygonF fragment;
    int sides = 6;

    for (int i = 0; i < sides; ++i) {
        double angle = i * 2 * M_PI / sides;
        // 添加随机变化使形状不规则
        double radiusVariation = 0.7 + 0.6 * qSin(angle * 3);
        double radius = size * radiusVariation;
        double x = center.x() + radius * qCos(angle);
        double y = center.y() + radius * qSin(angle);
        fragment << QPointF(x, y);
    }

    // === 绘制碎片 ===
    QLinearGradient fragmentGradient(center.x() - size, center.y() - size,
                                    center.x() + size, center.y() + size);
    fragmentGradient.setColorAt(0.0, color.lighter(130));
    fragmentGradient.setColorAt(1.0, color.darker(110));

    painter.setBrush(QBrush(fragmentGradient));
    painter.setPen(QPen(color.darker(150), 1));
    painter.drawPolygon(fragment);
}

/**
 * @brief 绘制UI元素
 * @param painter 绘图器
 */
void SnakeGameRenderer::drawUI(QPainter &painter)
{
    if (!m_gameState) {
        return;
    }

    painter.setPen(m_textColor);
    painter.setFont(m_gameFont);

    // === 绘制FPS信息 ===
    QString fpsText = QString("FPS: %1").arg(static_cast<int>(m_currentFPS));
    painter.drawText(10, 20, fpsText);

    // === 绘制游戏状态信息 ===
    QString statusText;
    switch (m_gameState->getGameStatus()) {
    case SnakeGameState::GameStatus::Waiting:
        statusText = "Waiting for players...";
        break;
    case SnakeGameState::GameStatus::Starting:
        statusText = "Game starting...";
        break;
    case SnakeGameState::GameStatus::Playing:
        statusText = "Playing";
        break;
    case SnakeGameState::GameStatus::Paused:
        statusText = "Paused";
        break;
    case SnakeGameState::GameStatus::Finished:
        statusText = "Game finished";
        break;
    case SnakeGameState::GameStatus::Error:
        statusText = "Error";
        break;
    }

    painter.drawText(10, 40, statusText);

    // === 绘制玩家分数 ===
    const SnakeData* playerSnake = m_gameState->getCurrentPlayerSnake();
    if (playerSnake) {
        QString scoreText = QString("Score: %1").arg(playerSnake->score);
        painter.drawText(10, 60, scoreText);

        QString lengthText = QString("Length: %1").arg(playerSnake->length);
        painter.drawText(10, 80, lengthText);
    }
}

/**
 * @brief 绘制调试信息
 * @param painter 绘图器
 */
void SnakeGameRenderer::drawDebugInfo(QPainter &painter)
{
    painter.setPen(Qt::yellow);
    painter.setFont(QFont("Arial", 8));

    // === 绘制坐标网格 ===
    if (m_gameState) {
        int boardWidth = m_gameState->getBoardWidth();
        int boardHeight = m_gameState->getBoardHeight();

        for (int x = 0; x < boardWidth; x += 5) {
            for (int y = 0; y < boardHeight; y += 5) {
                QPoint pixelPos = gameToPixelPosition(Position(x, y));
                painter.drawText(pixelPos + QPoint(2, 12), QString("%1,%2").arg(x).arg(y));
            }
        }
    }
}

/**
 * @brief 获取蛇的颜色
 * @param playerId 玩家ID
 * @param isHead 是否为蛇头
 * @return 蛇的颜色
 */
QColor SnakeGameRenderer::getSnakeColor(const QString &playerId, bool isHead) const
{
    // === 从主题获取蛇颜色 ===
    if (m_themes.contains(m_config.theme)) {
        QJsonObject theme = m_themes[m_config.theme];
        QJsonArray snakeColors = theme["snake_colors"].toArray();

        if (!snakeColors.isEmpty()) {
            // === 根据玩家ID选择颜色 ===
            int colorIndex = qHash(playerId) % snakeColors.size();
            QColor baseColor(snakeColors[colorIndex].toString());

            if (isHead) {
                // 蛇头颜色稍微亮一些
                return baseColor.lighter(120);
            } else {
                return baseColor;
            }
        }
    }

    // === 默认颜色 ===
    return isHead ? Qt::green : Qt::darkGreen;
}

/**
 * @brief 获取食物颜色
 * @param foodType 食物类型
 * @return 食物颜色
 */
QColor SnakeGameRenderer::getFoodColor(const QString &foodType) const
{
    // === 从主题获取食物颜色 ===
    if (m_themes.contains(m_config.theme)) {
        QJsonObject theme = m_themes[m_config.theme];

        if (foodType == "special" || foodType == "bonus") {
            return QColor(theme["special_food_color"].toString());
        } else {
            return QColor(theme["food_color"].toString());
        }
    }

    // === 默认颜色 ===
    if (foodType == "special" || foodType == "bonus") {
        return Qt::yellow;
    } else {
        return Qt::red;
    }
}

/**
 * @brief 获取单元格矩形
 * @param pos 游戏位置
 * @return 单元格矩形
 */
QRect SnakeGameRenderer::getCellRect(const Position &pos) const
{
    return getCellRect(pos.x, pos.y);
}

/**
 * @brief 获取单元格矩形
 * @param x X坐标
 * @param y Y坐标
 * @return 单元格矩形
 */
QRect SnakeGameRenderer::getCellRect(int x, int y) const
{
    int pixelX = x * m_config.cellSize;
    int pixelY = y * m_config.cellSize;
    return QRect(pixelX, pixelY, m_config.cellSize, m_config.cellSize);
}

/**
 * @brief 设置绘图器
 * @param painter 绘图器
 */
void SnakeGameRenderer::setupPainter(QPainter &painter)
{
    painter.setRenderHint(QPainter::Antialiasing, m_renderMode == Modern);
    painter.setRenderHint(QPainter::SmoothPixmapTransform, true);
}

/**
 * @brief 插值位置
 * @param from 起始位置
 * @param to 目标位置
 * @param progress 进度（0.0-1.0）
 * @return 插值后的位置
 */
Position SnakeGameRenderer::interpolatePosition(const Position &from, const Position &to, double progress) const
{
    double x = from.x + (to.x - from.x) * progress;
    double y = from.y + (to.y - from.y) * progress;
    return Position(static_cast<int>(x), static_cast<int>(y));
}
